package stdlib.net

import io.ktor.http.*
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.nio.charset.StandardCharsets


enum class ContentType(var value: String) {
    JSON("application/json;charset=utf-8"),
    WWW_FORM_URL_ENCODED("application/x-www-form-urlencoded;charset=utf-8")
}

fun encodeParams(contentType: ContentType, params: Map<String, String>?): String {
    if (params == null)
        return ""
    when (contentType) {
        ContentType.JSON -> {
            val buffer = StringBuffer("{")
            params.forEach {
                buffer.append("\"${it.key}\":\"${it.value}\",")
            }
            return "${buffer.removeSuffix(",")}}"
        }

        ContentType.WWW_FORM_URL_ENCODED -> {
            val buffer = StringBuffer()
            params.forEach {
                buffer.append(it.key).append("=").append(URLEncoder.encode(it.value, StandardCharsets.UTF_8)).append("&")
            }
            return buffer.removeSuffix("&").toString()
        }
    }
}

fun testHttpURLConnection(address: String, contentType: ContentType = ContentType.JSON, params: Map<String, String>?) {
    val url = URL(address)
    val urlConnection = url.openConnection() as HttpURLConnection
    val data = encodeParams(contentType, params).toByteArray()
    urlConnection.apply {
        requestMethod = "POST"
        readTimeout = 5000
        connectTimeout = 5000
        setRequestProperty("Connection", "keep-alive")
        setRequestProperty("Content-Type", "application/json")
        setRequestProperty("Content-Length", data.size.toString())
        doOutput = true
        doInput = true
    }

    val stream = urlConnection.outputStream
    stream.write(data)
    stream.flush()
    stream.close()
    urlConnection.connect()
    if (urlConnection.responseCode == 200) {
        val byteArrayOutputStream = ByteArrayOutputStream()
        val byteArrayOutputStream2 = ByteArrayOutputStream()
        var len: Int
        val buffer = ByteArray(1024)
        while (urlConnection.inputStream.read(buffer).also { len = it } != -1) {
            byteArrayOutputStream.write(buffer, 0, len)
        }
        urlConnection.inputStream.copyTo(byteArrayOutputStream2)
        urlConnection.inputStream.close()
        byteArrayOutputStream.close()
        val result = String(byteArrayOutputStream.toByteArray())
        println(result)
        println(byteArrayOutputStream.toString())
    } else {
        println(urlConnection.responseMessage)
    }
}


fun get(){
    val conn = URL("http://yzkj.mynetgear.com:7011/api/ping/P01010201202301110001").openConnection() as HttpURLConnection
    conn.requestMethod = "GET"
    println("${conn.responseCode}: ${conn.responseMessage}")
    val data =ByteArrayOutputStream()
    conn.inputStream.copyTo(data)
    conn.disconnect()
    println(data.toString())
}

fun main() {
//    val params = mapOf("test" to "test", "hello" to "world", "你好" to "世界")
//    println(encodeParams(ContentType.JSON, params))
//    println(encodeParams(ContentType.WWW_FORM_URL_ENCODED, params))
//    println(testHttpURLConnection("http://yzkj.mynetgear.com:7000/api/accounts/login", ContentType.JSON, mapOf("name" to "zing", "pwd" to "zing")))
    get()
}